#!/bin/bash

echo "🚀 启动 AI Chat 系统"
echo "=========================="

# 激活虚拟环境
echo "📦 激活虚拟环境..."
source .venv/bin/activate
echo "✅ 虚拟环境已激活"
echo ""

# 检查端口是否被占用
check_port() {
    local port=$1
    if lsof -i:$port > /dev/null 2>&1; then
        echo "⚠️  端口 $port 已被占用，正在清理..."
        lsof -ti:$port | xargs kill -9 2>/dev/null || true
        sleep 1
    fi
}

# 清理可能的旧进程
echo "🧹 清理旧进程..."
pkill -f "python.*api.py" 2>/dev/null || true
pkill -f "python.*backend.py" 2>/dev/null || true
pkill -f "npm.*dev" 2>/dev/null || true

# 前端端口，默认 4000（可通过环境变量 FRONTEND_PORT 覆盖）
FRONTEND_PORT=${FRONTEND_PORT:-4000}

# 检查并清理端口
check_port 8000
check_port 8100
check_port 8200
check_port $FRONTEND_PORT

echo "✅ 清理完成"
echo ""

# 启动模拟API (端口 8000, 8001)
echo "🤖 启动模拟AI API..."
nohup python3 api.py > logs/api.log 2>&1 &
API_PID=$!
echo "   PID: $API_PID"
echo "   HTTP: http://localhost:8000"
echo "   WebSocket: ws://localhost:8001"

# 等待API启动
sleep 2

# 启动后端API (端口 8200, 8100)
echo ""
echo "⚙️ 启动后端API..."
nohup python3 backend.py > logs/backend.log 2>&1 &
BACKEND_PID=$!
echo "   PID: $BACKEND_PID"
echo "   API: http://localhost:8200"
echo "   文件服务: http://localhost:8100"

# 等待后端启动
sleep 3

# 启动前端 (端口 $FRONTEND_PORT)
echo ""
echo "🌐 启动React前端..."
cd grok-chat
nohup npm run dev -- -p $FRONTEND_PORT > ../logs/frontend.log 2>&1 &
FRONTEND_PID=$!
cd ..
echo "   PID: $FRONTEND_PID"
echo "   地址: http://localhost:$FRONTEND_PORT"

# 保存PID到文件
mkdir -p logs
echo $API_PID > logs/api.pid
echo $BACKEND_PID > logs/backend.pid
echo $FRONTEND_PID > logs/frontend.pid

echo ""
echo "✅ 所有服务启动完成！"
echo ""
echo "📋 服务状态:"
echo "   模拟API:     http://localhost:8000"
echo "   后端API:     http://localhost:8200"
echo "   前端界面:    http://localhost:$FRONTEND_PORT"
echo "   文件服务:    http://localhost:8100"
echo ""
echo "📝 日志文件:"
echo "   API日志:     logs/api.log"
echo "   后端日志:    logs/backend.log"
echo "   前端日志:    logs/frontend.log"
echo ""
echo "🛑 停止服务: ./stop.sh"
